package com.apicommon.utils;

import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * description Nacos相关工具类
 *
 * @author tianzhou
 * @date 2024/4/28 11:24
 */
public class NacosUtils {

    private static NacosServiceManager nacosServiceManager;

    static  {
        nacosServiceManager = SpringContextUtils.getBean(NacosServiceManager.class);
    }

    /**
     * description 根据实例名字获取一个健康实例ip
     *
     * @param  instanceName
     * @return java.lang.String
     * @title getInstanceAdrByName
     * @author tianzhou
     * @date 2024/4/28 15:29
     */
    public static String getInstanceAdrByName(String instanceName) {
        Instance instance = null;
        try {
            instance = nacosServiceManager.getNamingService().selectOneHealthyInstance(instanceName);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
        return "http://" + instance.getIp() + ":" + instance.getPort();
    }

    /**
     * description 根据名字获取所有实例ip
     *
     * @param  instanceName
     * @return java.util.List<java.lang.String>
     * @title getAllInstanceAdrByName
     * @author tianzhou
     * @date 2024/4/28 15:30
     */
    public static List<String> getAllInstanceAdrByName(String instanceName) {
        List<Instance> allInstances = null;
        try {
           allInstances = nacosServiceManager.getNamingService().getAllInstances(instanceName);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
        List<String> ipList = allInstances.stream()
                .map(instance -> instance.getIp()).collect(Collectors.toList());
        return ipList;
    }
}
